package cn.nexd.app.presenter;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.text.TextUtils;

import com.umeng.analytics.MobclickAgent;

import cn.nexd.app.activity.MainActivity;
import cn.nexd.app.activity.inter.ISignInActivityView;
import cn.nexd.app.NexdApplication;
import cn.nexd.app.arsenal.R;
import cn.nexd.app.presenter.inter.ISignInPresenter;
import cn.nexd.app.util.MD5Util;
import cn.nexd.app.util.SharedPreferencesUtil;

/**
 * Created by wangxu on 16/3/28.
 */
public class ISignInPresenterImpl implements ISignInPresenter {
    private Context context;
    private ISignInActivityView iSignInActivityView;

    public ISignInPresenterImpl(Context context, ISignInActivityView iSignInActivityView) {
        this.context = context;
        this.iSignInActivityView = iSignInActivityView;
    }

    @Override
    public void signIn(String userEmail, String userPassword, boolean isSaveAccount) {
        if (NexdApplication.user.containsKey(userEmail)
                && NexdApplication.user.get(userEmail).getPassword()
                .equals(MD5Util.parseStrToMd5L32(userPassword))) {
            if (isSaveAccount) {
                SharedPreferencesUtil.saveAccount(context, userEmail);
            } else {
                SharedPreferencesUtil.saveAccount(context, "");
            }
            NexdApplication.userEmial = userEmail;
            NexdApplication.userName = NexdApplication.user.get(userEmail).getUserName();
            MobclickAgent.onProfileSignIn(userEmail);
            enterMainActivity();
        } else {
            iSignInActivityView.showToast("账户或密码错误,请重新输入或更新数据");
        }
    }

    private void enterMainActivity() {
        context.startActivity(new Intent(context, MainActivity.class));
        ((Activity) context).finish();
    }

    @Override
    public boolean checkUser(String userEmail, String userPassword) {
        if (TextUtils.isEmpty(userEmail)) {
            iSignInActivityView.setViewError("email不能为空", R.id.email);
            return false;
        } else if (TextUtils.isEmpty(userPassword)) {
            iSignInActivityView.setViewError("密码不能为空", R.id.password);
            return false;
        } else {
            return true;
        }
    }
}
